const plugin = requirePlugin('WechatSI')
const app = getApp()
const userInfo = wx.getStorageSync('userInfo');
const userId = userInfo.userid;
const recorderManager = wx.getRecorderManager()


Page({
  data: {
    videoUrl: '', // 修改为从空字符串开始
    messages: [],
    scrollTop: 0,
    inputValue: '',
    recording: false,
    isLoading: false,
    tempFilePath: '',
    innerAudioContext: null,
    speechRecognizer: null,
    interviewParams: null,
    currentPlayingAudio: null, // 新增当前播放标识
    animationData: {},
    lottieVisible: false,
    currentAnimation: 'idle',
    videoKey: Date.now()
  },

  onLoad(options) {
    if (options.params) {
      const params = JSON.parse(options.params);
      this.setData({
        interviewParams: {
          identity: params.identity,
          questionStyle: params.questionStyle,
          feedbackMode: params.feedbackMode,
          pressureLevel: params.pressureLevel,
          professionalism: params.professionalism,
          severity: params.severity,
          encouragement: params.encouragement,
          patience: params.patience
        }
      });
    }
    this.initSpeechRecognizer()
    this.initInterview()
  },
  onUnload() {
    this.cleanupResources()
  },
  async initInterview() {
    try {
      this.setData({ isLoading: true })
      const initResponse = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://pszap.top/chat/'+userId+'?type=job',
          method: 'GET',
          timeout: 150000,
          success: (res) => resolve(res.data),
          fail: (err) => reject(err)
        })
      })
      console.log(initResponse)
      await this.addInterviewerResponse(initResponse)
      // this.initSpeechRecognizer()
    } catch (err) {
      this.handleNetworkError(err)
    } finally {
      this.setData({ isLoading: false })
    }
  },
  async handleMessageFlow(content) {
    try {
      this.setData({ isLoading: true })
      await this.addUserMessage(content)
      const response = await new Promise((resolve, reject) => {
        wx.request({
          url: 'https://pszap.top/chat/'+userId+'?type=job',
          method: 'POST',
          timeout: 300000,
          data: {
            text: content,
            audio: this.data.tempFilePath
          },
          success: (res) => resolve(res.data),
          fail: (err) => reject(err)
        })
      })
      console.log(response)
      await this.addInterviewerResponse(response)
    } catch (err) {
      this.handleNetworkError(err)
    } finally {
      this.setData({ isLoading: false })
    }
  },
  createMessage(type, content, extra = {}) {
    return {
      type,
      content,
      time: new Date().toLocaleTimeString('zh-CN', { hour12: false }).slice(0, 5),
      ...extra
    }
  },
  // 修改 addInterviewerResponse 方法
  async addInterviewerResponse(response) {
    if (response.text) {
        await this.addMessage('interviewer', response.text)
    }
    if (response.audio) {
        const filePath = await this.saveBase64Audio(response.audio)
        const audioContext = this.data.innerAudioContext
        console.log(filePath)
        this.setData({ pendingAudio: filePath })
    }
    if(response.url) {
        // 先下载视频到本地再播放
        wx.downloadFile({
            url: response.url,
            success: (res) => {
                this.setData({
                    videoUrl: res.tempFilePath,
                    videoKey: Date.now()
                })
            },
            fail: (err) => {
                console.error('视频下载失败:', err)
                wx.showToast({ title: '视频加载失败', icon: 'none' })
            }
        })
    }
  },
  async addUserMessage(content) {
    await this.addMessage('me', content)
  },
  async addMessage(type, content, extra) {
    return new Promise(resolve => {
      this.setData({
        messages: [...this.data.messages, this.createMessage(type, content, extra)]
      }, () => {
        this.scrollToBottom()
        resolve()
      })
    })
  },
  initSpeechRecognizer() {
    const speechRecognizer = plugin.getRecordRecognitionManager()
    this.setData({ speechRecognizer })
    speechRecognizer.onStart = () => {
      this.setData({ 
        recording: true,
        inputValue: ''
      })
    }
    speechRecognizer.onRecognize = (res) => {
      if (res.result) {
        this.setData({ inputValue: res.result })
      }
    }
    speechRecognizer.onStop = (res) => {
      this.setData({ recording: false })
      if (res.result) {
        this.setData({ inputValue: res.result })
      }
    }
    speechRecognizer.onError = (err) => {
      console.error('识别错误:', err)
      this.setData({ recording: false })
      wx.showToast({ title: '识别失败', icon: 'none' })
    }
  },
  async saveBase64Audio(base64Data) {
      return new Promise((resolve, reject) => {
          const fs = wx.getFileSystemManager()
          const fileName = `${wx.env.USER_DATA_PATH}/audio_${Date.now()}.mp3`  // 修改为.mp3后缀
          
          // 移除base64前缀(如果有)
          const base64Str = base64Data.replace(/^data:audio\/\w+;base64,/, '')
          
          fs.writeFile({
              filePath: fileName,
              data: base64Str,  // 使用处理后的base64数据
              encoding: 'base64',
              success: () => resolve(fileName),
              fail: (err) => reject(err)
          })
      })
  },
  async scrollToBottom() {
      const query = wx.createSelectorQuery()
      query.select('.chat-container').scrollOffset(res => {
          this.setData({
              scrollTop: res.scrollHeight // 使用容器实际滚动高度
          })
      }).exec()
      
      // 添加延迟确保视图更新
      await new Promise(resolve => setTimeout(resolve, 100))
  },
  toggleRecord() {
    if (this.data.recording) {
      this.data.speechRecognizer.stop()
    } else {
      this.startRecording()
    }
  },
  startRecording() {
    this.data.speechRecognizer.start({
      lang: 'zh_CN',
      enableTranslate: true
    })
  },
  async sendMessage() {
    const content = this.data.inputValue.trim()
    if (!content) return

    this.setData({ inputValue: '' })
    this.handleMessageFlow(content)
  },
  onInput(e) {
    this.setData({ inputValue: e.detail.value })
  },

  // 修改 cleanupResources 方法
  cleanupResources() {
      if (this.data.recording) {
          this.data.speechRecognizer.stop()
      }
  },

  handleNetworkError(err) {
    console.error('请求失败:', err)
    wx.showToast({ title: '网络异常，请检查连接', icon: 'none' })
  },
  handleGenerateReport(){
    wx.navigateTo({
      url: '/pages/report/report',
    })
  },
  handleModifyProfile(){
    wx.navigateTo({
      url: '/pages/interviewer/interviewer',
    })
  },

})
